<!-- 购买商品模块 -->
<script>


    /**
     * 打开购买弹窗并显示商品详情
     * @param {Object} data - 当前商品数据
     * @param {Object} table - layui table 实例
     * @param {Object} form - layui form 实例
     * @param {Object} layer - layui layer 实例
     * @param {Object} $ - jQuery 实例
     */
    function openPurchasePopup(data, table, form, layer, $) {
        // 首先通过API获取商品的完整详情
        getProductDetail(data.pid, form, layer, $, function(detailData) {
            // 检查库存是否为0，如果为0则显示提示并不打开购买弹窗
            if (detailData.stock === 0) {
                layer.msg('该商品库存不足，暂时无法购买', { icon: 5 });
                return;
            }
            
            // 创建购买表单HTML
            var formHtml = `
            <div style="padding: 20px;">
                <!-- 商品详情展示 -->
                <div class="layui-row" style="margin-bottom: 20px;">
                    <div class="layui-col-md4">
                        <img src="${detailData.cover_url}" style="max-width: 200px; max-height: 200px; border-radius: 8px;">
                    </div>
                    <div class="layui-col-md8">
                        <h2 style="font-size: 20px; margin-bottom: 15px;">${detailData.name}</h2>
                        <div style="margin-bottom: 10px; font-size: 18px; color: #ff6700;">
                            <strong>价格：${detailData.points} 积分</strong>
                        </div>
                        <div style="margin-bottom: 10px;">
                            <strong>库存：</strong>${detailData.stock}
                        </div>
                        <div style="margin-bottom: 10px;">
                            <strong>已售：</strong>${detailData.sold}
                        </div>
                        <div style="margin-bottom: 10px;">
                            <strong>发货方式：</strong>${detailData.delivery_method}
                        </div>
                    </div>
                </div>
                
                <hr style="margin-bottom: 20px; border-top: 1px solid #e6e6e6;">
                
                <!-- 商品描述 -->
                <div style="margin-bottom: 20px;">
                    <h3 style="font-size: 16px; margin-bottom: 10px;">商品描述</h3>
                    <div style="padding: 10px; background-color: #f8f8f8; border-radius: 4px;">
                        ${detailData.description}
                    </div>
                </div>
                
                <!-- 购买确认 -->
                <form class="layui-form" lay-filter="purchaseForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">购买数量</label>
                        <div class="layui-input-block">
                            <input type="number" name="quantity" value="1" min="1" max="${detailData.stock}"
                                   lay-verify="required|number" class="layui-input" style="width: 100px;">
                            <span style="margin-left: 10px; color: #666;">库存：${detailData.stock}</span>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">所需积分</label>
                        <div class="layui-input-block">
                            <div id="totalPointsDisplay" style="line-height: 38px; font-size: 18px; color: #ff6700; font-weight: bold;">
                                ${detailData.points} 积分
                            </div>
                            <span style="margin-left: 10px; color: #999; font-size: 12px;">单价：${detailData.points} 积分/件</span>
                        </div>
                    </div>
                    <div class="layui-form-item" style="display: none;">
                        <input type="text" name="pid" value="${detailData.pid}">
                        <input type="text" name="name" value="${detailData.name}">
                        <input type="text" name="points" value="${detailData.points}">
                    </div>
                </form>
            </div>
            `;

            // 打开弹窗
            var index = layer.open({
                type: 1,
                title: '购买商品',
                content: formHtml,
                area: ['700px', 'auto'],
                btn: ['确认购买', '取消'],
                success: function (layero) {
                    // 刷新表单渲染
                    form.render();
                    
                    // 获取商品单价
                    var unitPrice = detailData.points;
                    
                    // 获取数量输入框
                    var quantityInput = layero.find('input[name="quantity"]');
                    
                    // 获取积分显示区域
                    var totalPointsDisplay = layero.find('#totalPointsDisplay');
                    
                    // 定义实时计算积分的函数
                    function updateTotalPoints() {
                        var quantity = parseInt(quantityInput.val()) || 1;
                        var totalPoints = quantity * unitPrice;
                        totalPointsDisplay.text(totalPoints + ' 积分');
                    }
                    
                    // 监听数量变化事件
                    quantityInput.on('input change', function() {
                        updateTotalPoints();
                    });
                },
                yes: function (index) {
                    // 获取表单数据
                    var formData = form.val('purchaseForm');

                    // 表单验证
                    var isError = false;
                    if (!formData.quantity || formData.quantity <= 0) {
                        layer.msg('购买数量不能为0，请输入有效的购买数量', { icon: 5 });
                        isError = true;
                    } else if (formData.quantity > detailData.stock) {
                        layer.msg('购买数量超过库存，请减少购买数量', { icon: 5 });
                        isError = true;
                    }

                    if (isError) {
                        return;
                    }

                    // 确认购买弹窗
                    layer.confirm('确认使用 ' + (formData.quantity * formData.points) + ' 积分购买 ' + formData.quantity + ' 件 "' + formData.name + '" 吗？', {
                        btn: ['确认', '取消']
                    }, function (confirmIndex) {
                        // 关闭确认框
                        layer.close(confirmIndex);
                        
                        // 发送请求进行购买
                        purchaseProduct(formData, table, layer, index);
                    });
                }
            });
        });
    }

    /**
     * 获取商品详情
     * @param {string} pid - 商品ID
     * @param {Object} form - layui form 实例
     * @param {Object} layer - layui layer 实例
     * @param {Object} $ - jQuery 实例
     * @param {Function} callback - 回调函数，处理获取到的商品详情
     */
    function getProductDetail(pid, form, layer, $, callback) {
        // 发送请求获取商品详情
        axios({
            url: '/api/product/get_product/',
            method: 'POST',
            data: {
                pid: pid
            },
        }).then(res => {
            res = res.data;
            if (res.code === 0) {
                // 调用回调函数处理商品详情
                callback(res.data);
            } else {
                layer.msg(res.message || '获取商品详情失败', { icon: 5 });
            }
        }).catch(() => {
            layer.msg('网络错误，请重试', { icon: 5 });
        });
    }

    /**
     * 执行购买商品操作
     * @param {Object} formData - 表单数据
     * @param {Object} table - layui table 实例
     * @param {Object} layer - layui layer 实例
     * @param {number} popupIndex - 弹窗索引
     */
    function purchaseProduct(formData, table, layer, popupIndex) {
        // 由于接口一次只能购买一个商品，所以循环处理购买数量
        var quantity = parseInt(formData.quantity);
        var purchasedCount = 0;
        var errorOccurred = false;
        
        // 显示加载中提示
        var loadingIndex = layer.load(2);
        
        // 定义购买单个商品的函数
        function purchaseSingle(pid, retryCount = 0) {
            if (errorOccurred || purchasedCount >= quantity) {
                // 所有购买完成或出现错误，关闭加载提示
                layer.close(loadingIndex);
                
                if (!errorOccurred && purchasedCount === quantity) {
                    layer.msg('商品购买成功', { icon: 6 });
                    layer.close(popupIndex);
                    // 刷新表格
                    table.reload('productTable');
                }
                return;
            }
            
            // 发送请求创建订单
            axios({
                url: '/api/order/create_order/',
                method: 'POST',
                data: {
                    product_id: pid
                },
            }).then(res => {
                res = res.data;
                if (res.code === 0) {
                    purchasedCount++;
                    // 继续购买下一个
                    purchaseSingle(pid);
                } else {
                    errorOccurred = true;
                    if (purchasedCount > 0) {
                        layer.msg(`部分购买成功，已购买 ${purchasedCount} 件，${res.message}`, { icon: 5 });
                    } else {
                        layer.msg(res.message || '购买失败', { icon: 5 });
                    }
                    purchaseSingle(pid);
                }
            }).catch(() => {
                // 重试机制，最多重试3次
                if (retryCount < 3) {
                    setTimeout(() => {
                        purchaseSingle(pid, retryCount + 1);
                    }, 500);
                } else {
                    errorOccurred = true;
                    if (purchasedCount > 0) {
                        layer.msg(`部分购买成功，已购买 ${purchasedCount} 件，网络错误，请重试`, { icon: 5 });
                    } else {
                        layer.msg('网络错误，请重试', { icon: 5 });
                    }
                    purchaseSingle(pid);
                }
            });
        }
        
        // 开始购买流程
        purchaseSingle(formData.pid);
    }
</script>